package ltd.hxya.novel.book.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ltd.hxya.novel.book.mapper.LastCrawlIndexMapper;
import ltd.hxya.novel.common.to.book.BookTo;
import ltd.hxya.novel.entity.crawl.LastCrawlIndex;
import ltd.hxya.novel.entity.rowdata.NovelRowData;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hty
 * @since 2022-11-19
 */
@Service
public class LastCrawlIndexServiceImpl extends ServiceImpl<LastCrawlIndexMapper, LastCrawlIndex>  {
    
    public void saveLastIndex( List<NovelRowData> novelRowDataList) {
        QueryWrapper<LastCrawlIndex> crawlIndexQueryWrapper = new QueryWrapper<>();
        for (NovelRowData novelRowData : novelRowDataList) {
            crawlIndexQueryWrapper.eq("crawl_source_id", novelRowData.getCrawlSourceId()).eq("crawl_book_id", novelRowData.getCrawlBookId());
            LastCrawlIndex lastCrawlIndex = this.getBaseMapper().selectOne(crawlIndexQueryWrapper);
            if (!ObjectUtils.isEmpty(lastCrawlIndex)){
                UpdateWrapper<LastCrawlIndex> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("crawl_source_id", novelRowData.getCrawlSourceId()).eq("crawl_book_id", novelRowData.getCrawlBookId()).set("last_index_name",novelRowData.getIndexName());
                this.update(updateWrapper);
                return;
            }
            //将最后一章的章节存入数据库中
            //LastCrawlIndex lastCrawlIndex = new LastCrawlIndex();
            lastCrawlIndex = new LastCrawlIndex();
            BeanUtils.copyProperties(novelRowData,lastCrawlIndex);
            lastCrawlIndex.setLastIndexName(novelRowData.getIndexName());
            lastCrawlIndex.setId(IdWorker.getIdStr());
            this.save(lastCrawlIndex);
        }
        
    }

    public LastCrawlIndex getLastIndex(BookTo book) {
        QueryWrapper<LastCrawlIndex> crawlIndexQueryWrapper = new QueryWrapper<>();
        crawlIndexQueryWrapper.eq("crawl_book_id", book.getCrawlBookId()).eq("crawl_source_id", book.getCrawlSourceId());
        LastCrawlIndex lastCrawlIndex = getBaseMapper().selectOne(crawlIndexQueryWrapper);
        return lastCrawlIndex;
    }

    public List<LastCrawlIndex> lastIndexList(Integer sourceId) {
        QueryWrapper<LastCrawlIndex> crawlIndexQueryWrapp = new QueryWrapper<>();
        crawlIndexQueryWrapp.eq("crawl_source_id",sourceId);
        List<LastCrawlIndex> lastCrawlIndices = baseMapper.selectList(crawlIndexQueryWrapp);
        return lastCrawlIndices;
    }
}
